<template>
    <div class="app-detail">
        <el-card class="box-card">
          <el-row :gutter="24" class="mb8 btnGroup">
                <el-col :span="6">
                    {{ $t('transferRules.ruleCode')+'：'+ ruleData.ruleCode }}
                </el-col>
                <el-col :span="6">
                    {{ $t('transferRules.ruleName')+'：'+ ruleData.ruleName }}
                </el-col>
                <el-col :span="6">
                    {{ $t('inspectionStandards.division')+'：'+ ruleData.divisionName }}
                </el-col>

            </el-row>
           <el-row :gutter="10" class="mb8 btnGroup">
                <el-col :span="1.5">
                    <el-button size="mini" type="primary" @click="handleAdd($t('btn.tianjia'))">
                        {{ $t('btn.tianjia') }}</el-button>
                </el-col>
            </el-row>
            <div class="container-table">
                <el-table class="table-fixed"   ref="multipleTable" :key="incomingKey" v-loading="loading" :height="tableHeight" border
                :data="incomingList"  >

                    <el-table-column :label="$t('transferRules.tacticsType')" sortable  align="left" prop="currentTactics" min-width="180" :show-overflow-tooltip="true" >
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                  {{formatNYIQC_RULE(scope.row.currentTactics)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.nameDescription')" sortable  align="left" prop="nameDescription" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.samplingType')" sortable  align="left" prop="samplingType" min-width="180" :show-overflow-tooltip="true" >
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <span  v-if="scope.row.samplingType=='1'">正常</span>
                                <span  v-if="scope.row.samplingType=='2'">放宽</span>
                                <span  v-if="scope.row.samplingType=='3'">加严</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.executionType')" sortable  align="left" prop="executionType" min-width="180" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <span  v-if="scope.row.executionType==1">批</span>
                                <span  v-if="scope.row.executionType==2">时间</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.cycleType')" sortable  align="left" prop="cycleType" min-width="180" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                            <div class="action-wrap">
                                  {{formatNYIQC_CYCLE(scope.row.cycleType)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.timeCycle')" sortable  align="left" prop="timeCycle" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.radius')" sortable  align="left" prop="radius" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.checkNum')" sortable  align="left" prop="checkNum" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.bitSkipping')" sortable  align="left" prop="startCheckNum" min-width="180" :show-overflow-tooltip="true" />
                     <el-table-column :label="$t('transferRules.triggerMode')" sortable  align="left" prop="triggerMode" min-width="180" :show-overflow-tooltip="true" >
                        <template slot-scope="scope">
                            <!-- 1：自动触发，2：手动触发 -->
                            <div class="action-wrap">
                                <span  v-if="scope.row.triggerMode=='1'">自动触发</span>
                                <span  v-if="scope.row.triggerMode=='2'">手动触发</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="140">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                               <table-body-btn type="view" :name="$t('home.view')" @click.native="onEdit(scope.row,$t('home.view'))" />
                               <table-body-btn type="edit" :name="$t('btn.edit')" @click.native="onEdit(scope.row,$t('public.edit'))" />
                               <table-body-btn type="delete" :name="$t('btn.delete')" @click.native="onDelete(scope.row)" />

                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>


           <div class="submit-footer" >
                <el-button icon="el-icon-close" size="small" class="drawer-close" @click="handleClose">{{$t('public.close')}}</el-button>

            </div>
        </el-card>
         <!-- 添加 -->
        <el-dialog :title="viewtitle" :visible.sync="typeOpen" center top="14vh"  width="1000px" :fullscreen="fullscreen" @close="close">
            <el-form :model="typeModel" size="small" label-suffix=":" ref="detailForm" :rules="rules" label-width="88px">
                <el-row :gutter="24" class="dia">
                    <el-col :span="12">
                        <el-form-item :label="$t('transferRules.currentTactics')" prop="currentTactics">
                            <el-select v-model="typeModel.currentTactics" :disabled="viewtitle=='查看'" :placeholder="$t('public.select_holder',{select_holder: $t('transferRules.currentTactics')})" clearable  size="small">
                                <el-option v-for="item in dict.type.NYIQC_RULE_TACTICS" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('transferRules.nameDescription')" prop="nameDescription">
                            <el-input v-model="typeModel.nameDescription" clearable  :disabled="viewtitle=='查看'"  size="small" :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.nameDescription')})" />
                        </el-form-item>
                    </el-col>

                     <el-col :span="24">
                        <el-divider content-position="center">{{ $t('transferRules.executionCondition') }}</el-divider>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('transferRules.samplingType')" prop="samplingType">
                             <el-select v-model="typeModel.samplingType"  :disabled="viewtitle=='查看'" clearable size="small" filterable :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.samplingType')})">
                                <el-option size="mini" v-for="item in samplingTypeList" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('transferRules.executionType')" prop="executionType">
                            <el-select v-model="typeModel.executionType"  :disabled="viewtitle=='查看'" :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.executionType')})" clearable  size="small">
                                <el-option key="1" label="批" value="1" />
                                <el-option key="2" label="时间" value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- 批状态 -->
                    <el-col :span="8" v-if="typeModel.executionType==1">
                        <el-form-item :label="$t('transferRules.radius')" prop="radius"  >
                            <el-input v-model="typeModel.radius" clearable  :disabled="viewtitle=='查看'"  size="small" :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.radius')})" />
                        </el-form-item>
                    </el-col>
                    <!-- 时间状态 -->
                    <el-col :span="8" v-if="typeModel.executionType==2">
                        <el-form-item :label="$t('transferRules.timeCycle')" prop="timeCycle">
                            <el-input v-model="typeModel.timeCycle" clearable :disabled="viewtitle=='查看'" size="small" :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.timeCycle')})"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8"  v-if="typeModel.executionType==2">
                        <el-form-item :label="$t('transferRules.cycleType')" prop="cycleType">
                            <el-select v-model="typeModel.cycleType" :disabled="viewtitle=='查看'"  :placeholder="$t('public.select_holder',{select_holder: $t('transferRules.cycleType')})" clearable  size="small">
                                <el-option v-for="item in dict.type.NYIQC_CYCLE_TYPE" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item :label="$t('transferRules.checkNum')" prop="checkNum">
                            <el-input-number :controls="false" v-model="typeModel.checkNum" clearable  :disabled="viewtitle=='查看'" :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.checkNum')})" size="small"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('transferRules.bitSkipping')" prop="startCheckNum">
                            <el-input-number :controls="false" v-model="typeModel.startCheckNum" clearable  :disabled="viewtitle=='查看'" :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.bitSkipping')})" size="small"/>
                        </el-form-item>
                    </el-col>


                    <!-- <el-col :span="6">
                        <el-form-item label="规则编号" prop="ruleCode">
                            <el-input v-model="typeModel.ruleCode" clearable   size="small" />
                        </el-form-item>
                    </el-col>  -->
                     <el-col :span="24">
                        <el-divider content-position="center">{{ $t('transferRules.triggerMode') }} </el-divider>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item :label="$t('transferRules.triggerMode')" prop="triggerMode">
                             <el-select v-model="typeModel.triggerMode"  :disabled="viewtitle=='查看'" clearable size="small" filterable>
                                <el-option size="mini" v-for="item in triggerModeList" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAdd" :loading="loading"  v-if="viewtitle!='查看'" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {listAllProject} from '@/api/basic/project'
import {mapGetters} from 'vuex'
import FileUpload from '@/components/FileUpload'
import printerDialog from '@/views/components/printerDialog'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import {
  carryOutAdd,
  carryOutDel,
  carryOutEdit,
  carryOutList,
  getTransferRulesInfo
} from "@/api/inspectionManagement/transferRules"
import EnjoySelectProject from "@/components/EnjoySelectProject";

export default {
    name: 'editMaterial',
    dicts: [
       'NYIQC_CYCLE_TYPE',
       'NYIQC_RULE_TACTICS'
    ],
    components: {
        FileUpload,
        printerDialog,
        SelectUserDialog,
        EnjoySelectProject
    },
    directives: {
        enterNumber: {
            inserted(el, binding, vnode, oldVnode) {
                el.addEventListener('keypress', function (e) {
                    e = e || window.event
                    let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode
                    let re = /^[0-9]\d*$/
                    if (
                        !re.test(String.fromCharCode(charcode)) &&
                        charcode > 9 &&
                        !e.ctrlKey
                    ) {
                        console.log(e)
                        if (e.preventDefault) {
                            e.preventDefault()
                        } else {
                            e.returnValue = false
                        }
                    }
                })
            },
        },
    },
    data() {
        var validateNumber = (rule, value, callback) => {
                if ((/^[1-9]\d*$/).test(value) || value == 0) {
                    callback()
                } else {
                    callback(new Error('请输入大于零的整数'))
                }
        }
        var validateNumberRange = (rule, value, callback) => {
                if ((/^[1-9]\d*$/).test(value) || value == 0) {
                    if(this.typeModel.executionType==1){
                        // 跳批数是指从总批数的第几个开始检验，需能够完整检验检验数
                        if(value <= (this.typeModel.radius - this.typeModel.checkNum + 1)){
                            callback()
                        }else{
                            callback(new Error('该跳批数无法完整检验检验数'))
                        }
                    }else{
                        callback()
                    }
                } else {
                    callback(new Error('请输入大于零的整数'))
                }
        }
        return {
            viewtitle:this.$t('btn.tianjia'),
            factoryList: [],


            showSearch: true,
            tableHeight: 'calc(100vh - 308px)',

            typeOpen: false,
            queryParams:{
                pageNum:1,
                pageSize:10
            },

            typeModel: {},

            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            stemList: [],
            // 总条数
            total: 0,
            // 字典表格数据
            incomingList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            selectRows: [],
            rowifInspect: '',
            // 查询参数

            // 表单参数
            form: {},
            // 表单校验
            rules: {

                currentTactics: [ {
                        required: true,
                        message: '当前策略不能为空',
                        change: 'blur',
                }],
                nameDescription: [ {
                        required: true,
                        message: '名称描述不能为空',
                        change: 'blur',
                }],
                 samplingType: [ {
                        required: true,
                        message: '抽样类型不能为空',
                        change: 'blur',
                }],
                executionType: [ {
                        required: true,
                        message: '执行类型不能为空',
                        change: 'blur',
                }],
                radius: [ { validator: validateNumber, trigger: 'blur' },{
                        required: true,
                        message: '批范围不能为空'
                }],
                checkNum: [  { validator: validateNumber, trigger: 'blur' },{
                        required: true,
                        message: '检验数不能为空'
                }],
                startCheckNum: [  { validator: validateNumberRange, trigger: 'blur' },{
                        required: true,
                        message: '跳批数不能为空'
                }],
                timeCycle: [  { validator: validateNumber, trigger: 'blur' },{
                        required: true,
                        message: '时间周期不能为空'
                }],
                cycleType: [ {
                        required: true,
                        message: '周期类型不能为空'
                }],
                 triggerMode: [ {
                        required: true,
                        message: '触发方式不能为空',
                        change: 'blur',
                }],
            },
            fullscreen: false,
            incomingKey: 0,
            projectList:[],
            //抽样类型 1：正常，2：放宽，3：加严
            samplingTypeList:[
                {value:"1",label:"正常"},
                {value:"2",label:"放宽"},
                {value:"3",label:"加严"},
            ],
             //触发方式（1：自动触发，2：手动触发）
            triggerModeList:[
                {value:"1",label:"自动触发"},
                {value:"2",label:"手动触发"}
            ],

            ruleData: {},   // 规则详情
        }
    },
    mounted() {
        this.getRuleInfo();
        this.getList()
        // this.getProjectList()
    },
    activated() {
        this.getRuleInfo();
        this.getList()

    },

    computed: {
        ...mapGetters(['userId', 'name', 'deptName']),
        // 获取 ruleId && ruleCode
        ruleId(){return this.$route.query.ruleId??''},
        ruleCode(){return this.$route.query.ruleCode??''},
    },

    methods: {
         formatNYIQC_RULE(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_RULE_TACTICS.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        formatNYIQC_CYCLE(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_CYCLE_TYPE.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        choseproject(e){
          this.typeModel.projectCodes=  this.projectList.filter(item=>item.projectName)[0].projectCode
        },
        close(){
            this.typeModel= { }
            this.$refs.detailForm.resetFields();
        },
         /** 新增按钮操作 */
        handleAdd(title) {
            this.typeModel={}
            this.typeOpen = true
            this.typeModel.startCheckNum ? '' : this.typeModel.startCheckNum = 1
            this.viewtitle=title
        },
        onEdit(row,title) {
            this.typeModel=JSON.parse(JSON.stringify(row))
            this.typeOpen = true
            this.typeModel.startCheckNum >= 0 ? '' : this.typeModel.startCheckNum = 1
            this.viewtitle=title
        },
        // 删除
        onDelete(row) {
             this.$modal.confirm(this.$t('formValidation.doYouConfirmDeletion')).then(() => {
                carryOutDel(row.id).then((response) => {
                    if (response.code == 200) {
                        this.$modal.msgSuccess(this.$t('tips.deleteSuccess'))
                        this.getList()
                    }
                })
            })
        },
         // 修改状态
        onStatus(row) {

        },
        // 提交添加
        submitAdd(){
            var data={
                ...this.typeModel,
                ruleCode:this.ruleCode
            }
            this.$refs.detailForm.validate((valid) => {
                if (valid) {

                    var action=this.typeModel.id ? carryOutEdit : carryOutAdd
                    action(data).then(res=>{
                       if (res.data) {
                         this.$message.success(this.typeModel.id?this.$t('formValidation.successfullyModified') : this.$t('formValidation.addedSuccessfully'))
                        this.getList()
                        this.typeOpen=false
                       } else {
                        this.$modal.msgError('已有当前策略类型')
                       }
                    })

                } else {
                    this.$modal.msgError(this.$t('formValidation.theBasicInformationIsIncomplete'))

                }
            })
        },
        getProjectList() {
            listAllProject().then((res) => {
                this.projectList = res.data
            })
        },
        /**  类型列表 */
        getList() {
            this.loading = true

            carryOutList({ruleCode:this.ruleCode}).then((response) => {
                if (response) {
                    this.incomingList = response.rows

                    this.total = response.total
                    this.loading = false

                }
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        handleClose(){
            this.$router.go(-1)
        },
        /** 获取规则详情  */
        getRuleInfo(){
            getTransferRulesInfo(this.ruleId).then(res=>{
                console.log('获取规则详情',res)
                if(res.code == 200 && res.data.id == this.ruleId) this.ruleData = res.data
            })
        }

    },
}
</script>
<style lang="scss" scoped>@import './index.scss';</style>
